import { Button, Card, message, Select, Table, Input } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import { filterAuth, findDicByCodeSort } from '@/support/common';
import AddModal from './addModal';
import EditModal from './editModal';
import styles from './index.less';

const { Option } = Select;

@connect(() => ({}))
export default class index extends PureComponent {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  state = {
    tenantCode: undefined,
    dataPermissionType: undefined,
    dataPermissionItemLevel: undefined,
    addModalVisible: false,
    editModalVisible: false,
    editModalData: null,
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    tableLoading: false,
    tenantList: [],
    permissionTypeList: [],
  };

  componentDidMount() {
    this.handleGetTenantList();
    this.handleGetPermissionTypeList();
    this.handleTableData();
  }

  //获取租户List
  handleGetTenantList = () => {
    this.props.dispatch({
      type: 'http/postDataWithRes',
      payload: {
        url: '/tenant/list',
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          this.setState({
            tenantList: response.data || [],
          });
        }
      },
    });
  };

  //获取权限类型
  handleGetPermissionTypeList = () => {
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/dict/finddictlistbycode',
        dictCode: 'DPItemType',
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          console.log('handleGetPermissionTypeList', response.data);
          this.setState({
            permissionTypeList: response.data || [],
          });
        }
      },
    });
  };

  handleTableData = () => {
    const { curPage, pageSize, tenantCode, dataPermissionType, dataPermissionItemLevel } = this.state;
    this.setState({
      tableLoading: true,
    });
    let submitData = {
      curPage,
      pageSize,
      tenantCode,
      dataPermissionType,
      dataPermissionItemLevel,
    };
    // console.log('dataPermissionItemLevel---', dataPermissionItemLevel)
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/datapermission/config/findpage',
        ...submitData,
      },
      callback: response => {
        if (response && response.statusCode == '0' && response.data) {
          if (response.data.list.length === 0 && response.data.pageNum > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data.list,
              total: response.data.total,
              selectedRowKeys: [],
            });
          }
        } else {
          if (response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleSearch = () => {
    this.handleTableData();
  };

  handleReset = () => {
    this.setState(
      {
        curPage: 1,
        pageSize: 10,
        tenantCode: undefined,
        dataPermissionType: undefined,
        dataPermissionItemLevel: '',
      },
      () => {
        this.handleTableData();
      },
    );
  };

  handleEdit = record => {
    this.setState({
      editModalVisible: true,
      editModalData: record,
    });
  };

  changeEditModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    } else {
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    }
  };

  handleDelete = record => {
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/datapermission/config/delete',
        sid: record.sid,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };

  handleAdd = () => {
    this.setState({
      addModalVisible: true,
    });
  };

  changeAddModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        addModalVisible: false,
      });
    } else {
      this.setState({
        addModalVisible: false,
      });
    }
  };

  render() {
    const {
      tenantCode,
      dataPermissionType,
      dataPermissionItemLevel,
      addModalVisible,
      editModalVisible,
      editModalData,
      tableData,
      total,
      curPage,
      pageSize,
      tableLoading,
      tenantList,
      permissionTypeList,
    } = this.state;

    // console.log('tenantList', tenantList);
    //  数据权限
    // const dpList = findDicByCodeSort(this.context.dicData,"DPItemType");

    const {
      location: { pathname },
    } = this.props;

    const columns = [
      // { title: '租户编码', dataIndex: 'tenantCode' },
      // { title: '租户名称', dataIndex: 'tenantName' },
      {
        title: '数据权限类型',
        dataIndex: 'itemType',
        render: text => {
          const findText = permissionTypeList.find(item => item.dictKey === text);
          return findText ? findText.dictValue : text;
        },
      },
      {
        title: '数据权限标签',
        dataIndex: 'itemLevel',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      {
        title: '数据权限值',
        dataIndex: 'itemValue',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      { title: '创建时间', dataIndex: 'createDate' },
      {
        title: '操作',
        dataIndex: 'opt',
        fixed: 'right',
        align: 'center',
        render: (text, record) => {
          const btns = [];

          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: 'tenantPermissionConfig_show',
            onConfirm: () => this.handleEdit(record),
          };

          /* const deleteBtn = {
            title: '删除',
            key: 'delete',
            Popconfirm: true,
            message: '确认删除？',
            auth: 'tenantPermissionConfig_show',
            onConfirm: () => this.handleDelete(record),
          }; */

          btns.push(editBtn);
          // btns.push(deleteBtn);
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };

    const tableProps = {
      columns,
      pagination,
      rowKey: 'sid',
      scroll: { x: 'max-content' },
      loading: tableLoading,
      dataSource: tableData,
      onChange: pagination => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
    };

    return (
      <div>
        <div className={styles.pateoSearch}>
          {/* <div className={styles.searchInputStr}>
            <div className={styles.title}>租户:</div>
            <Select
              value={tenantCode}
              placeholder="请选择租户"
              onChange={e => {
                this.setState({
                  tenantCode: e,
                });
              }}
            >
              {tenantList.map(tenant => {
                return (
                  <Option key={tenant.sid} value={tenant.tenantCode}>
                    {tenant.tenantName}
                  </Option>
                );
              })}
            </Select>
          </div> */}
          <div className={styles.searchInputStr}>
            <div className={styles.title}>数据权限类型:</div>
            <Select
              value={dataPermissionType}
              placeholder="请选择数据权限类型"
              onChange={e => {
                this.setState({
                  dataPermissionType: e,
                });
              }}
            >
              {permissionTypeList.map(permission => {
                return (
                  <Option key={permission.dictKey} value={permission.dictKey}>
                    {permission.dictValue}
                  </Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>数据权限标签:</div>
            <Input
              value={dataPermissionItemLevel}
              placeholder="请输入数据权限标签"
              onChange={e => {
                e.persist()
                this.setState({
                  dataPermissionItemLevel: e.target.value,
                });
              }}
            />
          </div>
          <div className={styles.searchBtn}>
            <Button
              onClick={() => this.handleSearch()}
              type={'primary'}
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button onClick={() => this.handleReset()}>重置</Button>
          </div>
        </div>
        <div className={styles.pateoBtns}>
          <div className={styles.btnItem}>
            <Button type="primary" onClick={() => this.handleAdd()}>
              新增数据权限
            </Button>
          </div>
        </div>
        <Card bordered={false} style={{ marginTop: 10 }}>
          <Table {...tableProps} />
        </Card>
        {addModalVisible ? (
          <AddModal
            tenantList={tenantList || []}
            permissionTypeList={permissionTypeList || []}
            changeAddModalVisible={this.changeAddModalVisible}
          />
        ) : null}
        {editModalVisible ? (
          <EditModal
            tenantList={tenantList || []}
            permissionTypeList={permissionTypeList || []}
            editModalData={editModalData}
            changeEditModalVisible={this.changeEditModalVisible}
          />
        ) : null}
      </div>
    );
  }
}
